package com.lq.controller.user;

import com.lq.entity.User;
import com.lq.exception.PasswordIncorrectException;
import com.lq.exception.UserIsNotExistException;
import com.lq.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user/login")
public class LoginServlet extends HttpServlet {
    UserService userService = new UserService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String verify = req.getParameter("verify");

        HttpSession session = req.getSession();
        String verfication = (String)session.getAttribute("verification");

//        resp.setHeader("Content-Type", "text/html;charset=UTF-8");
        if(!verfication.equals(verify)) {
            req.setAttribute("msg","验证码错误");
            req.getRequestDispatcher("/WEB-INF/pages/webpages/LoginError.jsp").forward(req, resp);
        }


        User user = new User();
        user.setUsername(username);
        user.setPassword(password);


        try{
            userService.login(user);
            //保存登录的状态
            session = req.getSession();
            session.setAttribute("user", user);
            //页面跳转
            resp.sendRedirect(req.getContextPath() + "/user");
        }catch (UserIsNotExistException e){
//                resp.getWriter().write("用户不存在");
            req.setAttribute("msg","用户名不存在");
            req.getRequestDispatcher("/WEB-INF/pages/webpages/LoginError.jsp").forward(req, resp);
        }catch(PasswordIncorrectException e){
//                resp.getWriter().write("密码错误");
            req.setAttribute("msg","密码错误");
            req.getRequestDispatcher("/WEB-INF/pages/webpages/LoginError.jsp").forward(req, resp);
        }


    }
}
